package com.car.shopping.controller;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.car.commons.core.util.JwtUtil;
import com.car.commons.web.util.WebUtil;
import com.car.shopping.controller.form.AddGoodsInfoForm;
import com.car.shopping.controller.form.FindGoodsForPageForm;
import com.car.shopping.entity.GoodsInfo;
import com.car.shopping.service.GoodsInfoService;
import com.car.commons.core.model.Result;
import com.car.shopping.service.dto.AddGoodsInfoDto;
import com.car.shopping.service.dto.GoodsDto;
import com.car.shopping.service.dto.GoodsInfoDto;
import com.car.shopping.service.param.AddGoodsInfoParam;
import com.car.shopping.service.param.ModifyGoodsInfoParam;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 董旭
 * @since 2024-08-28
 */
@RestController
@RequestMapping("/goodsInfo")
@Api(tags = "商品相关接口")
public class GoodsInfoController {
    @Autowired
    private GoodsInfoService goodsInfoService;
    /**
     * 通过商品ids
     * 返回一个商品dto的list
     * 并检查传入id的商品的商品类型状态是否正常
     *
     * @param ids 商品id的无序集合
     * @return 返回符合条件的商品信息
     * @throws Exception 异常处理
     */
    @GetMapping("/findGoodsInfoListByIds.ty")
    @ApiOperation("通过商品id集合查询商品且判断商品状态")
    public Result<List<GoodsInfoDto>> findGoodsInfoListByIds(@RequestParam Set<Integer> ids) throws Exception {
        // 参数校验
        if (ids == null || ids.isEmpty()) {
            return Result.getListResult(GoodsInfoDto.class).setMsg("商品ID集合不能为空").setCode(400);
        }
        // 调用服务层的方法获取商品信息
        List<GoodsInfoDto> goodsInfoList = goodsInfoService.findGoodsInfoListByIds(ids);
        // 检查商品类型状态
        for (GoodsInfoDto goods : goodsInfoList) {
            if (goods.getGoodsState() != 0) {  //0正常:1不正常
                throw new Exception("商品类型状态不正常: " + goods.getGoodsId());
            }
        }
        return Result.getListResult(GoodsInfoDto.class).setMsg("查询成功").setData(goodsInfoList);
    }


    @PostMapping("/findGoodsById.ty")
    @ApiOperation("通过id找到对应商品")
    public Result findGoodsById(@RequestBody Map<String, Integer> request) throws Exception {
        Integer id = request.get("id");
        if (id == null) {
            return Result.getResult().setMsg("缺少商品ID");
        }
        GoodsInfo goodsInfo = goodsInfoService.findGoodsById(id);
        return Result.getResult().setMsg("查询成功").setData(goodsInfo);
    }




    /**
     * 传入Set<GoodsDto>,通过id找到对应商品，然后修改其库存量和冻结量
     *
     * @param goods 商品Dto集合
     * @return 修改结果
     */
    @PostMapping("/reduceGoodsStock.ty")
    @ApiOperation("通过id找到对应商品，然后修改其库存量和冻结量")
    public Result updateGoodsStock(@RequestBody Set<GoodsDto> goods) {
        // 参数校验
        if (goods == null || goods.isEmpty()) {
            return Result.getResult().setMsg("商品集合不能为空").setCode(400);
        }
        //调方法更新
        goodsInfoService.updateGoodsStock(goods);
        return Result.getResult().setMsg("更新成功");
    }

   //新增商品
   @ApiOperation("新增商品信息")
   @PostMapping("/addGoods.pt")
   public Result<AddGoodsInfoForm> addGoods(
           @RequestParam("goodsName") String goodsName,
           @RequestParam("goodsTypeId") Integer goodsTypeId,
           @RequestParam(value = "goodsImg", required = false) MultipartFile goodsImg,
           @RequestParam("goodsStock") Integer goodsStock, // 商品库存量
           @RequestParam("goodsPrice") BigDecimal goodsPrice,
           @RequestParam("goodsDetail") String goodsDetail // 商品描述
   ) throws Exception {
       // 1. 从请求头中获取 token
       String token = WebUtil.getRequest().getHeader("car-token");
       System.out.println("////////////////////" + token);

       // 2. 从 token 中解析出 adminId
       Integer adminId = JwtUtil.getAdminId(token);

       // 3. 创建 AddGoodsInfoParam 对象
       AddGoodsInfoParam addGoodsInfoParam = new AddGoodsInfoParam();
       addGoodsInfoParam.setGoodsName(goodsName);
       addGoodsInfoParam.setGoodsTypeId(goodsTypeId);
       addGoodsInfoParam.setGoodsImg(goodsImg);
       addGoodsInfoParam.setGoodsStock(goodsStock);
       addGoodsInfoParam.setGoodsPrice(goodsPrice);
       addGoodsInfoParam.setGoodsDetail(goodsDetail);

       // 4. 调用服务层逻辑，新增商品
       AddGoodsInfoForm agd = goodsInfoService.addGoods(addGoodsInfoParam, adminId);

       // 5. 返回成功结果
       return Result.getResult(AddGoodsInfoForm.class).setMsg("新增商品成功").setData(agd).setCode(200);
   }


    //商品分页查询（根据名字模糊查询，根据类别查询）
    @ApiOperation("条件分页查询")
    @PostMapping("/findGoodsForPage.ty")
    public Result findGoodsForPage(@RequestBody FindGoodsForPageForm form)throws Exception{
        System.out.println(form);
        Page<GoodsInfo> result = goodsInfoService.findGoodsForPage(form);
        return Result.getResult().setMsg("查询成功").setData(result);
    }


    //修改商品信息
    @ApiOperation("修改商品信息")
    @PostMapping("/modifyGoods.pt")
    public Result modifyGoods(
            @RequestParam("goodsId") Integer goodsId,
            @RequestParam("goodsName") String goodsName,
            @RequestParam("goodsTypeId") Integer goodsTypeId,
            @RequestParam(value = "goodsImg", required = false) MultipartFile goodsImg,
            @RequestParam("goodsStock") Integer goodsStock,
            @RequestParam("goodsPrice") BigDecimal goodsPrice,
            @RequestParam("goodsDetail") String goodsDetail
    ) throws Exception {
        // 1. 从请求头中获取 token
        String token = WebUtil.getRequest().getHeader("car-token");

        // 2. 从 token 中解析出 adminId
        Integer adminId = JwtUtil.getAdminId(token);

        // 3. 创建 ModifyGoodsInfoParam 对象
        ModifyGoodsInfoParam modifyGoodsInfoParam = new ModifyGoodsInfoParam();
        modifyGoodsInfoParam.setGoodsId(goodsId);
        modifyGoodsInfoParam.setGoodsName(goodsName);
        modifyGoodsInfoParam.setGoodsTypeId(goodsTypeId);
        modifyGoodsInfoParam.setGoodsImg(goodsImg);
        modifyGoodsInfoParam.setGoodsStock(goodsStock);
        modifyGoodsInfoParam.setGoodsPrice(goodsPrice);
        modifyGoodsInfoParam.setGoodsDetail(goodsDetail);

        // 4. 调用服务层逻辑，修改商品信息
        goodsInfoService.modifyGoods(modifyGoodsInfoParam, adminId);

        // 5. 返回成功结果
        return Result.getResult().setMsg("修改商品信息成功").setCode(200);
    }




    /**
     * 支付后取消订单时，增加库存量
     *
     * @param goods 商品Dto集合
     * @return 操作结果
     */
    @PostMapping("/addGoodsStock.ty")
    @ApiOperation("支付后取消订单时增加库存量")
    public Result addStock(@RequestBody Set<GoodsDto> goods) {
        if (goods == null || goods.isEmpty()) {
            return Result.getResult().setMsg("商品集合不能为空").setCode(400);
        }
        goodsInfoService.addStock(goods);
        return Result.getResult().setMsg("库存增加成功").setCode(200);
    }

    /**
     * 下单但未支付时取消订单，增加库存量并减少冻结量
     *
     * @param goods 商品Dto集合
     * @return 操作结果
     */
    @PostMapping("/addGoodsStockAndReduceFreezeStock.ty")
    @ApiOperation("下单未支付取消订单时增加库存量并减少冻结量")
    public Result addStockAndReduceFreezeStock(@RequestBody Set<GoodsDto> goods) {
        if (goods == null || goods.isEmpty()) {
            return Result.getResult().setMsg("商品集合不能为空").setCode(400);
        }
        goodsInfoService.addStockAndReduceFreezeStock(goods);
        return Result.getResult().setMsg("库存增加且冻结量减少成功").setCode(200);
    }

    /**
     * 支付订单后减少冻结量
     *
     * @param goods 商品Dto集合
     * @return 操作结果
     */
    @PostMapping("/reduceGoodsFreezeStock.ty")
    @ApiOperation("支付订单后减少冻结量")
    public Result reduceFreezeStock(@RequestBody Set<GoodsDto> goods) {
        if (goods == null || goods.isEmpty()) {
            return Result.getResult().setMsg("商品集合不能为空").setCode(400);
        }
        goodsInfoService.reduceFreezeStock(goods);
        return Result.getResult().setMsg("冻结量减少成功").setCode(200);
    }


    /**
     * 支付回调时，减少库存量
     * 传入Set<GoodsDto>,通过id找到对应商品，减少库存量
     * @param goodsDtos 商品Dto集合
     * @return 修改结果
     */
    @PostMapping("/reduceStock.ty")
    @ApiOperation("支付回调时减少库存量")
    public Result reduceStock(@RequestBody Set<GoodsDto> goodsDtos) {
        // 参数校验
        if (goodsDtos == null || goodsDtos.isEmpty()) {
            return Result.getResult().setMsg("商品集合不能为空").setCode(400);
        }
        // 调用服务层的方法减少库存量
        goodsInfoService.reduceStock(goodsDtos);
        return Result.getResult().setMsg("库存减少成功");
    }
    @GetMapping("/findAll.ty")
    @ApiOperation("查询全部商品")
    public Result <List<GoodsInfo>> findAll() throws Exception{
        List<GoodsInfo> goods =  goodsInfoService.findAll();
        return Result.getListResult(GoodsInfo.class).setMsg("查询全部商品").setData(goods).setCode(200);
    }

    @PostMapping("/state.pt")
    @ApiOperation("更改商品状态")
    public Result state(@RequestBody Map<String, Integer> request) throws Exception {
        Integer goodsId = request.get("goodsId");
        goodsInfoService.state(goodsId);
        return Result.getResult().setMsg("改变商品状态成功").setCode(200);
    }


}

